Qt.include("Storage.js")

WorkerScript.onMessage = function(message) {
    doSessionTimeConnect(message)
}

function doSessionTimeConnect(message) {
    var xhr = new XMLHttpRequest();
    var url = "http://coscup.org/2011/api/program/"

    message.model.clear();
    WorkerScript.sendMessage({"result": "PROGRESS"});

    xhr.open("GET", url);
    xhr.onreadystatechange = function() {
        try {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                var response = JSON.parse(xhr.responseText);
                for (var i in response) {
                    var jsonData = response[i];
                    var from = timestamp2time(jsonData.from);
                    var to = timestamp2time(jsonData.to);

                    if (message.id == 1) {
                        if (jsonData.id <= 35) {
                            message.model.append({
                                                 schedule: from +
                                                 " - " + to,
                                                 name: jsonData.name,
                                                 speaker: jsonData.speaker

                        })
                        } else {
                            break;
                        }
                    } else if (message.id == 2) {
                        if (jsonData.id > 35 && jsonData.id <= 70) {
                            message.model.append({
                                                 schedule: from +
                                                 " - " + to,
                                                 name: jsonData.name,
                                                 speaker: jsonData.speaker

                        })
                        }
                    } else {
                        console.log("error");
                    }
                }
            }
            message.model.sync();
            WorkerScript.sendMessage({"result": "SUCCESS"});
        } catch (err) {
            WorkerScript.sendMessage({"result": "FAILURE"});
            //ERROR
        }
    }
    xhr.send();
}

function timestamp2time(unix_timestamp) {
    return Qt.formatTime(new Date(unix_timestamp * 1000), "hh:mm");
}
